<?php 

namespace app\seller\controller;
use app\common\model\Coupon as CouponModel;
use app\seller\controller\Base;
use app\seller\validate\CouponValidate;
use app\seller\event\CouponEvent;
use app\common\model\Goods;
use app\common\utils\JsonService;
use think\facade\View;


class Coupon extends Base{

    /**
    * 新增优惠劵
    * @return mixed
    */
    public function create(){
        if($this->request->isajax()){
            $post = $this->request->post();
            $validate = new CouponValidate;
            if(!$validate->scene('add')->check($post)) {
                return JsonService::error($validate->getError());
            }
            $post['shop_id'] = $this->shop_id;
            return CouponEvent::createCoupon($post);
        }
        return View::fetch();
    }

    /**
    * 编辑优惠劵
    * @return mixed
    */
    public function update(){
        if($this->request->isAjax()){
            $post = $this->request->post();
            $validate = new CouponValidate;
            if(!$validate->scene('edit')->check($post)) {
                return JsonService::error($validate->getError());
            }
            return CouponEvent::updateCoupon($post);
        }

        $id = $this->request->get('id');
        $model = $this->findModel($id);
        return View::fetch('update',[
            'model'=>$model,
        ]);
    }

    /**
    * 优惠劵列表

    * @return mixed
    */
    public function index(){
        $params = array_filter(request()->param());
        $dataProvider = CouponEvent::couponList($params);
        return View::fetch('index',['dataProvider'=>$dataProvider]);
    }


    /*
    * 删除优惠劵
    */
    public function delete(){
        if($this->request->isAjax()){
            $id = $this->request->param('id');
            try{
                $model = $this->findModel($id);
                $model->delete();
            }catch (\Exception $ex){
                return JsonService::error($ex->getMessage());
            }
            return JsonService::success('删除成功');
        }
    }

    /**
    * 得到模型
    *
    * @param int $id
    * @param array $where
    *
    * @return array|false|\PDOStatement|string|\think\Model
    */
    public function findModel($id,$where = [])
    {
        if (empty($id) && empty($where)) {
            throw new \think\exception\RouteNotFoundException();
        }
        return CouponModel::findModel($id, $where);
    }


    /*
     * 获取商品列表
     * */
    public function ajaxGetGoods(){
        $where = [];
        $goods = Goods::where($where)->field('goods_id,shop_id,goods_name,shop_price,original_img,goods_type,sales_sum,store_count,figure_nu,comment_count')->select()->toArray();
        return JsonService::success($goods);

    }

}
